package org.i1510.common.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.i1510.common.bean.PageBean;
import org.i1510.common.dao.ISysAttDao;
import org.i1510.common.po.SysAtt;
import org.i1510.common.service.ISysAttService;
import org.i1510.common.utils.DateUtils;
import org.i1510.common.utils.IDGenerator;
import org.i1510.common.utils.KBProperties;
import org.i1510.common.utils.StringUtils;
import org.i1510.common.utils.UserUtils;
import org.i1510.common.utils.file.FileUtils;
import org.i1510.common.utils.file.ZipUtils;
import org.i1510.common.utils.web.ResultMapper;
import org.i1510.common.utils.web.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping(value = "/admin/sysAtt")
public class SysAttController extends BaseController {
	private static final Logger logger = LoggerFactory
			.getLogger(SysAttController.class);
	@Autowired
	private ISysAttService iSysAttService;
	@Autowired
	private ISysAttDao iSysAttDao;

	private ResultMapper mapper;

	/**
	 * @Author Rambo
	 * @Desc：保存对象
	 * @param sysAtt
	 * @param errors
	 * @return TODO
	 * @Version SysAttController.java,v 1.1 2013-11-15 下午4:20:56
	 */
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	@ResponseBody
	public String save(HttpServletRequest request,
			@Valid @ModelAttribute("sysAtt") SysAtt sysAtt, BindingResult errors) {

		if (errors.hasErrors()) {
			mapper = WebUtils.getMapper4Errors(errors);
		} else {
			mapper = iSysAttService.save(sysAtt, request);
		}

		return mapper.toJson();
	}

	/**
	 * @Author Rambo
	 * @Desc：删除对象
	 * @param docId
	 * @param errors
	 * @return TODO
	 * @Version SysAttController.java,v 1.1 2014-9-2 下午3:38:17
	 */
	@RequestMapping(value = "/deleteX", method = RequestMethod.POST)
	@ResponseBody
	public String deleteX(@Valid @ModelAttribute("docId") String docId,
			BindingResult errors) {

		if (errors.hasErrors()) {
			mapper = WebUtils.getMapper4Errors(errors);
		} else {
			mapper = iSysAttService.delete(docId);
		}

		return mapper.toJson();
	}

	/**
	 * @Author Rambo
	 * @Desc：查看对象
	 * @param docId
	 * @param errors
	 * @return TODO
	 * @Version SysAttController.java,v 1.1 2014-9-2 下午3:39:35
	 */
	@RequestMapping(value = "/view", method = RequestMethod.GET)
	@ResponseBody
	public String view(@Valid @ModelAttribute("docId") String docId,
			BindingResult errors) {
		ResultMapper mapperRtn = ResultMapper.generateFailure();
		if (errors.hasErrors()) {
			mapperRtn = WebUtils.getMapper4Errors(errors);
		} else {
			SysAtt sysAtt = iSysAttService.findById(docId);
			mapperRtn = ResultMapper.generateSuccess();
			mapperRtn.appendResult("data", sysAtt);
		}
		return mapperRtn.toJson();
	}

	@RequestMapping(value = "/list", method = RequestMethod.GET)
	@ResponseBody
	public String list(@ModelAttribute("fromDate") String fromDate,
			@ModelAttribute("toDate") String toDate,
			@Valid @ModelAttribute("sysAtt") SysAtt sysAtt,
			@Valid @ModelAttribute("pageBean") PageBean pageBean,
			BindingResult errors) {
		ResultMapper mapperRtn = ResultMapper.generateFailure();
		if (errors.hasErrors()) {
			mapperRtn = WebUtils.getMapper4Errors(errors);
		} else {
			Map conditions = new HashMap();
			conditions.put("fromDate", fromDate);
			conditions.put("toDate", toDate);
			List sysAtts = iSysAttService.getPage(sysAtt, pageBean, conditions);
			int totalCount = iSysAttService.getPageCount(sysAtt, conditions);
			Map map = new HashMap();
			map.put("pageNo", pageBean.getPageNo());
			map.put("pageSize", pageBean.getPageSize());
			map.put("totalCount", totalCount);
			map.put("listData", sysAtts);

			mapperRtn = ResultMapper.generateSuccess();
			mapperRtn.appendResult("data", map);
		}
		return mapperRtn.toJson();
	}

	/**
	 * @Author Rambo
	 * @Desc：状态修改
	 * @param request
	 * @param docId
	 * @param docStatus
	 * @param errors
	 * @return TODO
	 * @Version CateController.java,v 1.1 2014-9-11 上午10:06:04
	 */
	@RequestMapping(value = "/updateStatus", method = RequestMethod.POST)
	@ResponseBody
	public String updateStatus(HttpServletRequest request,
			@Valid @ModelAttribute("docId") String docId,
			@Valid @ModelAttribute("docStatus") String docStatus,
			BindingResult errors) {

		if (errors.hasErrors()) {
			mapper = WebUtils.getMapper4Errors(errors);
		} else {
			if (!StringUtils.isStringEmpty(docId)) {
				SysAtt sysAtt = new SysAtt();

				sysAtt.setDocId(docId);
				sysAtt.setDocStatus(docStatus);
				mapper = iSysAttService.save(sysAtt, request);
			} else {
				mapper = ResultMapper.generateFailure();
				mapper.appendResult("messages", "无法找到该ID!");
			}

		}

		return mapper.toJson();
	}

	/**
	 * @Author Rambo
	 * @Desc：多文件上传
	 * @param files
	 * @param request
	 * @param model
	 * @param sysAtt
	 * @param errors
	 * @return TODO
	 * @Version SysAttController.java,v 1.1 2014-9-12 下午3:55:14
	 */
	@RequestMapping(value = "/uploads", method = RequestMethod.POST)
	@ResponseBody
	public String uploads(
			@RequestParam(value = "files", required = false) MultipartFile[] files,
			HttpServletRequest request, ModelMap model,
			@Valid @ModelAttribute("sysAtt") SysAtt sysAtt, BindingResult errors) {
		mapper = ResultMapper.generateFailure();
		if (files != null && files.length > 0) {
			if (isFileAccess(files)) {
				String root = KBProperties.FILEUPLOAD;
				File dirTemp = new File(root);
				if (!dirTemp.exists()) {
					try {
						dirTemp.mkdirs();
					} catch (Exception ex) {
						try {
							throw new Exception("不能创建目录 :" + root);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
				for (int i = 0; i < files.length; i++) {
					MultipartFile file = files[i];
					if (!file.isEmpty()) {
						// 文件传输
						String docId = IDGenerator.getGenerateID();
						InputStream is;
						try {
							is = file.getInputStream();
							File destFile = new File(root, docId);
							OutputStream os = new FileOutputStream(destFile);

							byte[] buffer = new byte[KBProperties.INPUTMAX];
							int length = 0;
							while ((length = is.read(buffer)) > 0) {
								os.write(buffer, 0, length);
							}

							is.close();
							os.close();

							sysAtt.setDocId(docId);
							sysAtt.setAttPath(root);
							sysAtt.setDocStatus("10");
							sysAtt.setAttSuffix(file.getContentType());
							sysAtt.setDocCreateTime(DateUtils.getNow());
							sysAtt.setDocCreator(UserUtils
									.getSessionUserBean(request).getSysUser()
									.getDocId());
							sysAtt.setDocSubject(file.getOriginalFilename()
									.toLowerCase());
							sysAtt.setKeyword("FILEUPLOAD");
							SysAtt saved = iSysAttDao.save(sysAtt);
							if (saved != null) {
								mapper = ResultMapper.generateSuccess();
							} else {
								mapper.appendResult("message", "索引保存失败!");
							}

						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

					}

				}
			}

		}

		return mapper.toJson();
	}

	/**
	 * @Author Rambo
	 * @Desc：单一文件上传
	 * @param file
	 * @param request
	 * @param model
	 * @param sysAtt
	 * @param errors
	 * @return TODO
	 * @Version SysAttController.java,v 1.1 2014-9-12 上午10:47:31
	 */
	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	@ResponseBody
	public String upload(
			@RequestParam(value = "file", required = false) MultipartFile file,
			HttpServletRequest request, ModelMap model,
			@Valid @ModelAttribute("sysAtt") SysAtt sysAtt, BindingResult errors) {
		mapper = ResultMapper.generateFailure();
		if (!file.isEmpty()) {
			MultipartFile[] files = new MultipartFile[1];
			files[0] = file;
			if (isFileAccess(files)) {
				// 文件类型判断
				String root = KBProperties.FILEUPLOAD;
				File dirTemp = new File(root);
				if (!dirTemp.exists()) {
					try {
						dirTemp.mkdirs();
					} catch (Exception ex) {
						try {
							throw new Exception("不能创建目录 :" + root);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
				// 文件传输
				String docId = IDGenerator.getGenerateID();
				InputStream is;
				try {
					is = file.getInputStream();
					File destFile = new File(root, docId);
					OutputStream os = new FileOutputStream(destFile);

					byte[] buffer = new byte[KBProperties.INPUTMAX];
					int length = 0;
					while ((length = is.read(buffer)) > 0) {
						os.write(buffer, 0, length);
					}

					is.close();
					os.close();

					sysAtt.setDocId(docId);
					sysAtt.setAttPath(root);
					sysAtt.setDocStatus("10");
					sysAtt.setAttSuffix(file.getContentType());
					sysAtt.setDocCreateTime(DateUtils.getNow());
					sysAtt.setDocCreator(UserUtils.getSessionUserBean(request)
							.getSysUser().getDocId());
					sysAtt.setDocSubject(file.getOriginalFilename()
							.toLowerCase());
					sysAtt.setKeyword("FILEUPLOAD");
					SysAtt saved = iSysAttDao.save(sysAtt);
					if (saved != null) {
						mapper = ResultMapper.generateSuccess();
					} else {
						mapper.appendResult("message", "索引保存失败!");
					}

				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		}
		return mapper.toJson();
	}

	/**
	 * @Author Rambo
	 * @Desc：判断文件是否合法
	 * @param files
	 * @return TODO
	 * @Version SysAttController.java,v 1.1 2014-9-12 下午4:08:12
	 */
	public boolean isFileAccess(MultipartFile[] files) {

		List<String> fileTypes = new ArrayList<String>();
		for (int i = 0; i < files.length; i++) {
			fileTypes.add(files[i].getContentType());
		}
		if (isAllowedType(fileTypes)) {// 类型不符合

		} else {
			return false;
		}
		return true;
	}

	/**
	 * @author Kenshinbo@163.com
	 * @描述：过滤文件类型
	 * @param fileContentType
	 * @return
	 * @version UploadAction.java,v 1.1 Dec 29, 2010 4:18:09 PM KB
	 */
	public boolean isAllowedType(List<String> fileContentType) {
		return true;
		// String fileType = KBProperties.FILETYPE;
		// if (fileContentType != null && fileContentType.size() > 0) {
		// for (int i = 0; i < fileContentType.size(); i++) {
		// if (!fileType.contains(fileContentType.get(i).toString())) {
		// return false;
		// }
		// }
		// return true;
		// }
		// return false;
	}

	/**
	 * @Author Rambo
	 * @Desc：下载文件
	 * @param response
	 * @param docId
	 * @param errors
	 * @return TODO
	 * @Version SysAttController.java,v 1.1 2014-9-15 下午11:16:57
	 */
	@RequestMapping(value = "/download", method = RequestMethod.GET)
	@ResponseBody
	public String download(HttpServletResponse response,
			@Valid @ModelAttribute("docId") String docId, BindingResult errors) {
		ResultMapper mapperRtn = ResultMapper.generateFailure();
		if (errors.hasErrors()) {
			mapperRtn = WebUtils.getMapper4Errors(errors);
		} else {
			SysAtt sysAtt = iSysAttService.findById(docId);
			if (null != sysAtt) {

				InputStream is;
				try {
					is = new FileInputStream(new File(sysAtt.getAttPath() + "/"
							+ sysAtt.getDocId()));
					response.setContentType("octet-stream");
					response.setHeader(
							"Content-Disposition",
							"attachment; filename="
									+ new String(sysAtt.getDocSubject()));
					OutputStream outputStream;
					try {
						outputStream = response.getOutputStream();
						byte[] buffer = new byte[KBProperties.INPUTMAX];
						int i = -1;
						while ((i = is.read(buffer)) != -1) {
							outputStream.write(buffer, 0, i);
						}
						outputStream.flush();
						outputStream.close();
						is.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			} else {
				mapper.appendResult("message", "找不到附件!");
				return mapper.toJson();
			}

		}
		return null;
	}

	/**
	 * @Author Rambo
	 * @Desc：根据ids 多文件下载压缩包
	 * @param response
	 * @param docIds
	 * @param errors
	 * @return TODO
	 * @Version SysAttController.java,v 1.1 2014-9-15 下午11:36:21
	 */
	@RequestMapping(value = "/downloads", method = RequestMethod.GET)
	@ResponseBody
	public String downloads(HttpServletResponse response,HttpServletRequest request, String[] docIds,@Valid @ModelAttribute("sysAtt") SysAtt sysAtt,
			BindingResult errors) {
		ResultMapper mapperRtn = ResultMapper.generateFailure();
		if (errors.hasErrors()) {
			mapperRtn = WebUtils.getMapper4Errors(errors);
		} else {
			List docList = Arrays.asList(docIds);
			List<SysAtt> sysAttList = iSysAttService.findByIds(docList);			
			if (sysAttList.size() > 0) {
				String rootUser = KBProperties.ZIPTEMP+"/["+DateUtils.getNowExt1()+"]"+UserUtils.getSessionUserBean(request).getSysUser().getName();
				String root = KBProperties.ZIPTEMP;
				String downloadId = IDGenerator.getGenerateID();
			
				try {
					
					File dirTemp = new File(rootUser);
					if (!dirTemp.exists()) {
						try {
							dirTemp.mkdirs();
						} catch (Exception ex) {
							try {
								throw new Exception("不能创建目录 :" + rootUser);
							} catch (Exception e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					}
					File[] files = new File[sysAttList.size()];
					for (int i = 0; i < sysAttList.size(); i++) {
						FileUtils.copy2(sysAttList.get(i).getAttPath() + "/"+ sysAttList.get(i).getDocId(), rootUser+"/"+sysAttList.get(i).getDocSubject());
						files[i] = new File(rootUser+"/"+sysAttList.get(i).getDocSubject());
					}
					ZipUtils.zipFileList(files, root + "/"+downloadId+".zip", "");
					InputStream is;
					is = new FileInputStream(new File(root + "/"+downloadId+".zip"));
					response.setContentType("octet-stream");
					response.setHeader("Content-Disposition",
							"attachment; filename="
									+ new String("downloadZip.zip"));
					OutputStream outputStream;
					try {
						outputStream = response.getOutputStream();
						byte[] buffer = new byte[KBProperties.INPUTMAX];
						int i = -1;
						while ((i = is.read(buffer)) != -1) {
							outputStream.write(buffer, 0, i);
						}
						outputStream.flush();
						outputStream.close();
						is.close();
						//删除zipTemp的临时文件目录（非zip文件）
						FileUtils.deleteDir(new File(rootUser));
					} catch (FileNotFoundException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} else {
				mapper.appendResult("message", "找不到附件列表!");
				return mapper.toJson();
			}

		}
		return null;
	}
}